package vn.vtsmart.vtcalendarsync;

import java.util.Calendar;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements OnClickListener {

	private static final int FILE_NAME_CODE = 1001;
	private Button mBtnBrowrse;
	private Button mBtnSync;
	private EditText mEdtFileName;
	private TextView mTvAppName;
	private String mFileName;
	private ListView mListView;
	private CalendarParser mParser;
	private CalendarListAdapter mListAdapter;
	private List<CalendarNameItem> mData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		mBtnBrowrse = (Button) findViewById(R.id.btnBrowser);
		mBtnSync = (Button) findViewById(R.id.btnSync);
		mEdtFileName = (EditText) findViewById(R.id.edtFileName);
		mTvAppName = (TextView) findViewById(R.id.tvAppName);
		mListView = (ListView) findViewById(R.id.lstCalendar);
		mBtnBrowrse.setOnClickListener(this);
		mBtnSync.setOnClickListener(this);

		mBtnBrowrse.setTypeface(Utils.getFontFromAssets(this, Utils.FONT_NAME));
		mBtnSync.setTypeface(Utils.getFontFromAssets(this, Utils.FONT_NAME));
		mEdtFileName
				.setTypeface(Utils.getFontFromAssets(this, Utils.FONT_NAME));
		mTvAppName.setTypeface(Utils.getFontFromAssets(this,
				Utils.FONT_TITLE_NAME));
		mEdtFileName.setEnabled(false);
		mBtnSync.setVisibility(View.INVISIBLE);

	}

	private void createParser() {
		// TODO Auto-generated method stub
		if (mEdtFileName.getText() == null)
			return;
		String fileName = mEdtFileName.getText().toString();
		if (fileName == null)
			return;
		mParser = new CalendarParser(fileName);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == mBtnBrowrse) {
			openFileBrowser();
		} else if (v == mBtnSync) {
			syncToCalendar();
			// importCalendar(0);
			// createEvent();
		}
	}

	private void syncToCalendar() {
		// TODO Auto-generated method stub
		int size = mData.size();
		for (int i = 0; i < size; i++) {
			if (mData.get(i).ismIsChecked() == true) {
				importCalendar(mData.get(i).getmSheetNumber());
			}
		}
	}

	private void importCalendar(int index) {
		// TODO Auto-generated method stub

		List<CalendarEvent> eventList = mParser.parse(index);
		int sizeEvent = eventList.size();

		for (int i = 0; i < sizeEvent; i++) {
			createCalendarEvent(eventList.get(i));
			// Log.d("DungNT", eventList.get(i).getDescription());
		}
	}

	private void openFileBrowser() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("file/*");
		startActivityForResult(intent, FILE_NAME_CODE);
	}

	private void createCalendarEvent(CalendarEvent e) {
		// TODO Auto-generated method stub
		ContentResolver cr = getContentResolver();
		ContentValues values = new ContentValues();
		long startMillis = e.getmStartMillis();
		long endMillis = e.getmEndMillis();
		long calID = 1;
		values.put(Events.DTSTART, startMillis);
		values.put(Events.DTEND, endMillis);
		values.put(Events.EVENT_LOCATION, e.getmLocation());
		values.put(Events.TITLE, e.getmContent());
		values.put(Events.CALENDAR_ID, calID);
		values.put(Events.DESCRIPTION, e.getDescription());
		values.put(Events.EVENT_TIMEZONE, "Asia/Saigon");
		Uri uri = cr.insert(Events.CONTENT_URI, values);
		Log.d("DungNT", "Insert : " + uri.toString());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == FILE_NAME_CODE) {
			if (resultCode == RESULT_OK) {
				mFileName = data.getData().getPath();
				mEdtFileName.setText(mFileName);
				createParser();
				if (mParser == null)
					return;
				mData = mParser.getAllSheetName();
				mListAdapter = new CalendarListAdapter(this, mData);
				mListView.setAdapter(mListAdapter);
				mBtnSync.setVisibility(View.VISIBLE);
			}
		}
	}

	private void createEvent() {
		long calID = 1;
		ContentResolver cr = getContentResolver();
		ContentValues values = new ContentValues();
		long startMillis = 0;
		long endMillis = 0;
		Calendar beginTime = Calendar.getInstance();
		beginTime.set(2014, 11, 17, 8, 0);
		startMillis = beginTime.getTimeInMillis();

		Calendar endTime = Calendar.getInstance();
		endTime.set(2014, 11, 17, 8, 30);
		endMillis = endTime.getTimeInMillis();

		values.put(Events.DTSTART, startMillis);
		values.put(Events.DTEND, endMillis);
		values.put(Events.TITLE, "Jazzercise");
		values.put(Events.DESCRIPTION, "Group workout");
		values.put(Events.CALENDAR_ID, calID);
		values.put(Events.EVENT_TIMEZONE, "America/Los_Angeles");
		Uri uri = cr.insert(Events.CONTENT_URI, values);
		cr.delete(Events.CONTENT_URI, null, null);
	}

	private void queryCalendar() {
		String[] EVENT_PROJECTION = new String[] { Calendars._ID, // 0
				Calendars.ACCOUNT_NAME, // 1
				Calendars.CALENDAR_DISPLAY_NAME, // 2
				Calendars.OWNER_ACCOUNT // 3
		};

		int PROJECTION_ID_INDEX = 0;
		int PROJECTION_ACCOUNT_NAME_INDEX = 1;
		int PROJECTION_DISPLAY_NAME_INDEX = 2;
		int PROJECTION_OWNER_ACCOUNT_INDEX = 3;
		Cursor cur = null;
		ContentResolver cr = getContentResolver();
		Uri uri = Calendars.CONTENT_URI;
		// Submit the query and get a Cursor object back.
		cur = cr.query(uri, EVENT_PROJECTION, null, null, null);

		// Use the cursor to step through the returned records
		while (cur.moveToNext()) {
			long calID = 0;
			String displayName = null;
			String accountName = null;
			String ownerName = null;

			// Get the field values
			calID = cur.getLong(PROJECTION_ID_INDEX);
			displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
			accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
			ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);

			// Do something with the values...
			Log.d("DungNT", "calID = " + calID + ", displayName = "
					+ displayName + ", accountName = " + accountName
					+ ", ownerName = " + ownerName + "\n");
		}
	}
}
